
#include <stdio.h>
#include <wiringPi.h>
#include <time.h>



// LED Pin - wiringPi pin 0 is BCM_GPIO 17.

#define	LED	0
#define LED7    7
#define DEBUG   3

FILE *ofp;
int first = 0;
clock_t begin, end;
time_t t;
struct tm ldt;

void benny()
{
  double time_spent;
  float power;
  char sname[200];


  digitalWrite (LED, LOW);
  end = clock();
  time_spent = (double)(end-begin)/CLOCKS_PER_SEC;
  begin = clock();
  power = 3600/time_spent;

  if(first == 1 && power < 10000.)
  {
     int x = (int)power;
     digitalWrite (DEBUG, HIGH);
     time(&t);
     ldt = *localtime(&t);

     sprintf(sname,"/var/www/bess-%d-%d-%d.txt",ldt.tm_year+1900,ldt.tm_mon+1,ldt.tm_mday);
     ofp = fopen(sname, "a+");
     fprintf(ofp,"%d, %d, %d, %d, %d, %d, %d \n",ldt.tm_year+1900,ldt.tm_mon+1,ldt.tm_mday,ldt.tm_hour,ldt.tm_min,ldt.tm_sec,x);
     fclose(ofp);

     ofp = fopen("/var/www/bess.html", "w");
    // Format 2013-06-02 09:34:15  2013 5 433 10 80 18
     fprintf(ofp,"%d-%d-%d %d:%d:%d  %d Watts \n",ldt.tm_year+1900,ldt.tm_mon+1,ldt.tm_mday,ldt.tm_hour,ldt.tm_min,ldt.tm_sec,x);
     fclose(ofp);

     printf("%d-%d-%d %d:%d:%d ", ldt.tm_year + 1900, ldt.tm_mon + 1, ldt.tm_mday, ldt.tm_hour, ldt.tm_min, ldt.tm_sec);
     printf("%d\n",x);

     delay(10);
     //sprintf(shttp,"wget -O temp.txt -q 'bess.simuino.com/data.php?user=1&time=2013&puls=5&power=%d&base=10&sigmax=80&temp=18'",x);
     //printf("%s\n",shttp);
     //system(shttp);
     digitalWrite (DEBUG, LOW);
  }
  else
   first = 1;
}

//=======================================================
int main (void)
{
  wiringPiSetup () ;
  pinMode (LED, OUTPUT) ;
  pinMode (LED7,INPUT);
  pinMode (DEBUG,OUTPUT);

  printf("BESS running...\n");
  begin = clock();
//INT_EDGE_FALLING, INT_EDGE_RISING, INT_EDGE_BOTH or INT_EDGE_SETUP
  wiringPiISR (LED7, INT_EDGE_FALLING, benny) ;


  for (;;)
  {
  }

}
